/*
 * Copyright (c) 2023 Cshoo Org. All Rights Reserved.
 */

package org.cshoo.tattoo.embed.infra.utils;

import com.google.gson.Gson;
import org.cshoo.tattoo.embed.infra.entity.User;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author 杨翼
 * @since 1.0
 */
public class UserUtils {

    /**
     * 获取当前用户
     *
     * @return 用户
     */
    public static User getUser() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String userHeader = request.getHeader("user");
        if (Objects.nonNull(userHeader)) {
            return new Gson().fromJson(userHeader, User.class);
        }

        User anonymousUser = new User();
        anonymousUser.setId(-1L);
        anonymousUser.setName("anonymous");
        anonymousUser.setUsername("anonymous");
        return anonymousUser;
    }
}
